﻿using System.Collections.Generic;
using KPIS.GERP.Models.Class;
using KPIS.GERP.Models.ICM;
using Resources;
using System;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace KPIS.GERP.WEB.GIMS.Controllers
{
    // [AccessDeniedAuthorize]
    public class PenaltyController : Controller
    {
        //
        // GET: /Penalty/
        public ActionResult Index(int PoId)
        {
            ViewBag.PoId = PoId;
            try
            {
                using (var service = new PurchaseOrderService.PurchaseOrderServiceClient())
                {
                   
                    var model = service.SelectPoPenalty(new PurchaseOrderPenalty { PoId = PoId }, new[] { "PurchaseOrder", "PenaltyRateType" });
                    return View(model);
                }
            }
            catch(Exception ex){
                ModelState.AddModelError(ErrorLocalization.Error, ErrorLocalization.ErrorWhileDeleteData);
                GerpLog.Error(ErrorLocalization.ErrorWhileDeleteData + ", " + ex.Message);
                return View(new List<PurchaseOrderPenalty>());
            }
        }

        public ActionResult Create(int PoId)
        {
            var model = new PurchaseOrderPenalty();
            model.PoId = PoId;
           // ViewBag.PoId = PoId;
            return View(model);            
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult Create(PurchaseOrderPenalty model, FormCollection collection)
        {
            StringBuilder message_error = new StringBuilder();
            message_error.Append("<div class='alert alert-error'>");
            message_error.Append("<button type='button' class='close' data-dismiss='alert'>");
            message_error.Append("<i class='icon-remove'></i>");
            message_error.Append("</button>");
            message_error.Append("<strong>");
            message_error.Append("<i class='icon-remove'></i>");
            message_error.Append(" พบข้อผิดพลาด: ");
            message_error.Append("</strong>");

            if (model == null)
            {
                message_error.Append("กรอกข้อมูลไม่ครบถ้วน!");
                message_error.Append("</div>");
                return Json(new { success = false, message = message_error.ToString() });
            }

            try
            {
                if (ModelState.IsValid)
                {
                    var service = new PurchaseOrderService.PurchaseOrderServiceClient();
                    var id = service.InsertPoPenalty(model, Class.GimsMembership.CurrentEmpId);
                    message_error = new StringBuilder();
                    message_error.Append("<div class='alert alert-block alert-success'>");
                    message_error.Append("<button type='button' class='close' data-dismiss='alert'>");
                    message_error.Append("<i class='icon-remove'></i>");
                    message_error.Append("</button>");
                    message_error.Append("<strong>");
                    message_error.Append("<i class='icon-ok'></i>");
                    message_error.Append(" บันทึกข้อมูล: ");
                    message_error.Append("</strong>");
                    message_error.Append("สร้างใบสั่งซื้อเรียบร้อยแล้ว");
                    message_error.Append("</div>");
                    return Json(new { id = id, success = true, message = message_error.ToString() });
                    // return RedirectToAction("Details", new { id });            
                }
                else {
                    message_error.Append("กรอกข้อมูลไม่ครบถ้วน!");
                    message_error.Append("</div>");
                    return Json(new { success = false, message = message_error.ToString() });
                }
            }catch(Exception ex){
                GerpLog.Error(ErrorLocalization.ErrorWhileDeleteData + ", " + ex.Message);
                ModelState.AddModelError(ErrorLocalization.Error, ErrorLocalization.ErrorWhileDeleteData);
                message_error.Append(ex.Message);
                message_error.Append("</div>");
                return Json(new { success = false, message = message_error.ToString() });  
            }
            
            //return View(model);
        }

        public ActionResult Details(int id)
        {
            try
            {
                using (var service = new PurchaseOrderService.PurchaseOrderServiceClient())
                {
                    var polst = service.SelectPoPenalty(new PurchaseOrderPenalty { PoPenId = id }, new[] { "PurchaseOrder" });
                    return View(polst.FirstOrDefault());
                }
            }
            catch (Exception ex)
            {
                GerpLog.Error(ErrorLocalization.ErrorWhileDeleteData + ", " + ex.Message);
                return View(new PurchaseOrderPenalty());
            }
        }

        public ActionResult Delete(int id)
        {
            try
            {
                using (var service = new PurchaseOrderService.PurchaseOrderServiceClient())
                {
                    int? poid = service.DeletePoPenalty(id, Class.GimsMembership.CurrentEmpId);
                    //return RedirectToAction("/Index?PoId=" + poid);
                    return Redirect("~/Penalty/Index?PoId=" + poid);
                }

                
            }
            catch (Exception ex)
            {
                GerpLog.Error(ErrorLocalization.ErrorWhileDeleteData + ", " + ex.Message);
                ModelState.AddModelError("พบข้อผิดพลาด!", "ไม่สามารถลบข้อมูลได้");
                return Json(new { success = false });
               // return View("Index");
            }
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult DeleteAll(int[] deleteIds)
        {
            StringBuilder message_error = new StringBuilder();
            message_error.Append("<div class='alert alert-error'>");
            message_error.Append("<button type='button' class='close' data-dismiss='alert'>");
            message_error.Append("<i class='icon-remove'></i>");
            message_error.Append("</button>");
            message_error.Append("<strong>");
            message_error.Append("<i class='icon-remove'></i>");
            message_error.Append(" พบข้อผิดพลาด: ");
            message_error.Append("</strong>");


            if (deleteIds == null)
            {
                message_error.Append("กรุณาเลือกข้อมูลที่ต้องการลบ!");
                message_error.Append("</div>");
                return Json(new { deleteIds = deleteIds, success = false, message = message_error.ToString() });
            }

            try
            {
                using (var service = new PurchaseOrderService.PurchaseOrderServiceClient())
                {
                    foreach (int delete in deleteIds)
                    {
                        service.DeletePoPenalty(delete, Class.GimsMembership.CurrentEmpId);
                    }

                }

                message_error = new StringBuilder();
                message_error.Append("<div class='alert alert-block alert-success'>");
                message_error.Append("<button type='button' class='close' data-dismiss='alert'>");
                message_error.Append("<i class='icon-remove'></i>");
                message_error.Append("</button>");
                message_error.Append("<strong>");
                message_error.Append("<i class='icon-ok'></i>");
                message_error.Append(" ลบข้อมูล: ");
                message_error.Append("</strong>");
                message_error.Append("ลบข้อมูลเรียบร้อยแล้ว!");
                message_error.Append("</div>");
                ModelState.AddModelError(ErrorLocalization.Error, string.Format("ลบข้อมูลไปทั้งหมด {0} รายการ", deleteIds.Length.ToString("#,##0")));
                return Json(new { success = true, message = message_error.ToString() });
                //return Json(new { success = true });
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(ErrorLocalization.Error, ErrorLocalization.ErrorWhileDeleteData);
                GerpLog.Error(ErrorLocalization.ErrorWhileDeleteData + ", " + ex.Message);
                return Json(new { success = false });
            }
        }

        public ActionResult Edit(int id)
        {
            try
            {
                using (var service = new PurchaseOrderService.PurchaseOrderServiceClient())
                {
                    var model = service.SelectPoPenalty(new PurchaseOrderPenalty { PoPenId = id }, null);                  
                    return View(model.FirstOrDefault());
                }
            }
            catch (Exception ex)
            {
                GerpLog.Error(ErrorLocalization.ErrorWhileDeleteData + ", " + ex.Message);
                return View(new PurchaseOrderPenalty());
            }

        }

        [HttpPost]
        public ActionResult Edit(PurchaseOrderPenalty model, FormCollection collection)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    using (var service = new PurchaseOrderService.PurchaseOrderServiceClient())
                    {
                        var penlst = service.SelectPoPenalty(new PurchaseOrderPenalty { PoPenId = model.PoPenId },null).ToList();
                        penlst.ForEach(l => new Action(delegate()
                        {
                            l.Name = model.Name; l.Descr = model.Descr; l.PenaltyRate = model.PenaltyRate;l.RateTypeId = model.RateTypeId;
                        }).Invoke());
                        service.UpdatePoPenalty(model, Class.GimsMembership.CurrentEmpId);
                        return Redirect("~/Penalty/Index?PoId=" + penlst.FirstOrDefault().PoId);
                    }
                    
                    //return RedirectToAction("Index");
                }
                return View(model);
            }
            catch (Exception ex)
            {
                GerpLog.Error(ErrorLocalization.ErrorWhileDeleteData + ", " + ex.Message);
                return View(model);
                //throw ex;
            }
        }
    }
}
